import { Toast } from 'vant'
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      num: 0,
      showTabbar: true
    },
    children: [
      {
        path: 'popup',
        name: 'MyPopup',
        component: () => import('../views/MyPopup.vue')
      }
    ]
  },
  {
    path: '/category',
    name: 'Category',
    meta: {
      num: 2,
      showTabbar: true
    },
    component: () => import('../views/Category.vue')
  },
  {
    path: '/cart',
    name: 'Cart',
    meta: {
      num: 3,
      showTabbar: true
    },
    component: () => import('../views/Cart.vue')
  },
  {
    path: '/topic',
    name: 'Topic',
    meta: {
      num: 1,
      showTabbar: true
    },
    component: () => import('../views/Topic.vue')
  },
  {
    path: '/user',
    name: 'User',
    meta: {
      num: 4,
      showTabbar: true
    },
    component: () => import('../views/User.vue')
  },
  {
    path: '/productdetail',
    name: 'ProductDetail',
    component: () => import('../components/ProductDetail.vue')
  }
]

const router = new VueRouter({
  routes
})

// 前置路由，
// 3个参数
// to即将到达的路由
// from 即将离开的路由
// next()其实是一个函数, 每一个导航守卫必须至少搭配一个next()
// 否则它就无法跳到下一步 后置守卫不需要next()所以后置守卫会有两个参数
router.beforeEach((to, from, next) => {
  // 想要进入购物车，必须有token
  let token = localStorage.getItem('token')
  if (to.path == '/cart') {
    if (token) {
      next()
    } else {
      Toast.fail('请先登录')
      // 定时器
      setTimeout(() => {
        next({ name: 'User' })
      }, 1000)
    }
    return
    // 此时必须要有token
  }
  next()
})

export default router
